package wpp.view;

import wpp.WPP;
import javafx.animation.Animation;
import javafx.animation.RotateTransition;
import javafx.animation.RotateTransitionBuilder;
import javafx.animation.Timeline;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.control.Separator;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.HBox;
import javafx.util.Duration;

public class MainButtonSet extends HBox {
	
	private Button localPreviewBtn;
	private Button favorBtn;
	private RotateTransition localPreviewBtnRoTransition;
	private RotateTransition favorBtnRoTransition;
	
	public MainButtonSet() {
		this.setId("main-button-set");
		addControl();
		addEvent();
	}
	
	private void addControl() {
		localPreviewBtn = newButton("localPreview");
		favorBtn = newButton("favor");
		localPreviewBtnRoTransition = newBtnRoTransition(localPreviewBtn);
		favorBtnRoTransition = newBtnRoTransition(favorBtn);
		this.getChildren().addAll(localPreviewBtn, favorBtn, new Separator());
	}
	
	private void addEvent() {
		localPreviewBtn.setOnMouseEntered(eventOnBtnEntered(localPreviewBtnRoTransition));
		localPreviewBtn.setOnMouseExited(eventOnBtnExited(localPreviewBtnRoTransition, localPreviewBtn));
		localPreviewBtn.setOnAction(eventOnBtnAction(localPreviewBtn));
		favorBtn.setOnMouseEntered(eventOnBtnEntered(favorBtnRoTransition));
		favorBtn.setOnMouseExited(eventOnBtnExited(favorBtnRoTransition, favorBtn));
		favorBtn.setOnAction(eventOnBtnAction(favorBtn));
	}
	
	//Control
	private Button newButton(String css) {
		Button btn = new Button();
		btn.getStyleClass().add(css);
		btn.setPrefSize(65, 50);
		return btn;
	}
	
	private RotateTransition newBtnRoTransition(Button btn) {
		RotateTransition transition = RotateTransitionBuilder.create()
				.duration(Duration.millis(200))
				.fromAngle(-5)
				.toAngle(5)
				.cycleCount(Timeline.INDEFINITE)
				.autoReverse(true)
				.node(btn)
				.build();
		return transition;
	}
	
	//Event	
	private EventHandler<MouseEvent> eventOnBtnEntered(final Animation animation) {
		return new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent e) {
				animation.play();
			}			
		};
	}
	
	private EventHandler<MouseEvent> eventOnBtnExited(final Animation animation, final Button btn) {
		return new EventHandler<MouseEvent>() {
			@Override
			public void handle(MouseEvent arg0) {
				animation.stop();	
				btn.setRotate(0);
			}
		};
	}
	
	private EventHandler<ActionEvent> eventOnBtnAction(final Button btn) {
		return new EventHandler<ActionEvent>() {
			@Override
			public void handle(ActionEvent arg0) {
				if(btn == localPreviewBtn) {
					WPP.showLocalPreviewPane();
				} else if(btn == favorBtn) {
					WPP.showFavorPane();
				}
			}
		};
	}
}
